package com.lightsaber.cut.entity;

import java.util.ArrayList;
import java.util.List;

public class Original implements Comparable<Original> {

    private Integer length;
    private List<Component> group = new ArrayList<Component>();

    public Original(Integer length) {

        super();
        this.length = length;
    }

    public void setLength(Integer length) {

        this.length = length;
    }

    public List<Component> getGroup() {
        return group;
    }

    public Integer getLength() {

        return length;
    }

    /**
     * 实际使用长度
     * 
     * @return
     */
    public Integer getUsedLength() {

        Integer usedLength = 0;
        for (Component component : group) {
            usedLength += component.getLength();
        }

        return usedLength;
    }

    /**
     * 剩余长度
     * 
     * @return
     */
    public Integer getSurplus() {
        return length - getUsedLength();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(this.length * 1.0 / 1000 + "m料, 切割: ");
        for (Component co : group) {
            sb.append(co.getLength() * 1.0 / 1000 + "(" + co.getSequence() + "), ");
        }
        sb.append("; ");
        sb.append("余料: " + this.getSurplus() * 1.0 / 1000 + "\r\n");

        return sb.toString();
    }

    /**
     * 组合之前先判别能不能添加进来
     * 
     * @param component
     *            要组合进来的尺寸
     * @return true: 组合进来, false: 不能组合进来
     * @throws Exception
     */
    public void cut(Component component) throws Exception {

        if (getSurplus() < component.getLength()) {
            throw new Exception(String.format("即将添加进来的尺寸(%f)会溢出整料长", component.getLength()));
        }

        this.group.add(component);
    }

    @Override
    public int compareTo(Original o) {
        return this.getSurplus().compareTo(o.getSurplus());
    }
}
